/*
 * Created on 2004-12-23
 *
 * 
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.dcivision.form.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.dcivision.form.FormErrorConstant;
import com.dcivision.form.dao.FormElementDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.web.AbstractActionForm;

/**
 * @author Administrator
 *
 * 
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class MaintUploadImgToImportFileAction extends com.dcivision.framework.web.AbstractMaintAction{
  

  /** getFunctionCode
  *
  * Abstract function which sub-class should implement to return the corresponding
  * function code.
  *
  * @return   The function code
  */
  public String getFunctionCode() {
    return(SystemFunctionConstant.FORM_SETUP);
  }

  /** getMajorDAOClassName
  *
  * Abstract function which sub-class should implement to return the corresponding
  * major DAO class name used in this class.
  *
  * @return   The DAO class name
  */
  public String getMajorDAOClassName() {
    return("com.dcivision.form.dao.FormElementDAObject");
  }

  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    InputStream inputStream = null;
    FileOutputStream fos = null;
    int bufferSize = 8192;
    byte[] buffer = new byte[bufferSize];
    int length = -1;
    boolean isFileError = false;
    String tmpName=null;
    
    try {
      MaintUploadImgToImportFileForm maintForm = (MaintUploadImgToImportFileForm) form;
      String filePath = SystemParameterFactory.getSystemParameter(SystemParameterConstant.FORM_ATTACHMENT_PHYSICAL_PATH);
      FormElementDAObject formElementDAO = new FormElementDAObject(this.getSessionContainer(request),this.getConnection(request));
      HashMap nameMap = new HashMap();
      for (int i=1; i<=3; i++) {
        FormFile tmpFile=null;
        //log.debug("i="+i);

        //log.debug("class name: "+maintForm.getClass().toString());
        Method getFileMth = maintForm.getClass().getMethod("getUploadFile"+i, null);
        //log.debug("get file method name: "+getFileMth.getName());
        Method getFileNameMth = maintForm.getClass().getMethod("getFileName"+i, null);
        //log.debug("get true file method name: "+getFileMth.getName());
        tmpFile = (FormFile)getFileMth.invoke(maintForm, null);
        tmpName = (String)getFileNameMth.invoke(maintForm, null);
      
        if (tmpFile != null) {
          if (!"".equals(tmpFile.getFileName())) {
            String uploadImageName = Math.random() + tmpFile.getFileName().substring(tmpFile.getFileName().indexOf("."),tmpFile.getFileName().length());
            String originalName = TextUtility.formatFileName(tmpName);
            log.debug("file name from form file: "+tmpName);
			File dirFile = new File(filePath); 
            if (!dirFile.exists()){ 
              throw new ApplicationException(FormErrorConstant.FORM_NO_PATH_OF_THE_ATTACHMENT);
            }

            File convertedFile = new File(filePath + "/" + uploadImageName);
            inputStream = tmpFile.getInputStream();
            fos = new FileOutputStream(convertedFile);
            if(tmpFile.getFileSize()==0){
              isFileError= true;
              log.debug("invalid picture file: ");
              throw new ApplicationException("form.error.message.invalid_picture_file",null,tmpName);
            }
            while ((length=inputStream.read(buffer, 0, bufferSize)) != -1) {
              fos.write(buffer, 0, length);
            }
            fos.flush();
            inputStream.close();
            fos.close();            
            nameMap.put("fileName"+i, uploadImageName+"|"+originalName);        
          }
        }
      }
      request.setAttribute("nameMap",nameMap);
    } catch (IOException ioe) {
      log.debug("io exception in getUploadFileList: "+ioe);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, ioe);
    } catch (ApplicationException ape) {
      if(isFileError){
        throw new ApplicationException("form.error.message.invalid_picture_file",null,tmpName);
      }else{
    	throw new ApplicationException(FormErrorConstant.FORM_NO_PATH_OF_THE_ATTACHMENT);
      }
    } catch (Exception e) {
      log.debug("exception in getUploadFileList: "+e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {
      try { inputStream.close(); } catch (Exception ignore) {}
      try { fos.close(); } catch (Exception ignore) {}
    }
  }
  
  
}
